﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Akronus.TaskScheduler
{
    /// <summary>
    /// Manages task schedule if task is scheduled to run on specific time of the day.
    /// </summary>
    public class TimeTaskScheduleStrategy : ITaskScheduleStrategy
    {
        private DateTime time;

        /// <summary>
        /// Initializes a new instance of the <see cref="TimeTaskScheduleStrategy"/> class.
        /// </summary>
        /// <param name="time">The time.</param>
        public TimeTaskScheduleStrategy(DateTime time)
        {
            this.time = time;
        }

        /// <summary>
        /// Gets the task schedule.
        /// </summary>
        /// <returns>the <see cref="TaskSchedule"/>.</returns>
        public virtual TaskSchedule GetTaskSchedule()
        {
            if (DateTime.Now.TimeOfDay >= time.TimeOfDay)
            {
                var currentDate = DateTime.Now;
                DateTime nextRun = currentDate.AddDays(1);
                TimeSpan newTime = nextRun.Subtract(DateTime.Now);
                return new TaskSchedule() { Interval = newTime.TotalMilliseconds, RunTaskImmediately = false };
            }
            else
            {
                TimeSpan newTime = time.TimeOfDay.Subtract(DateTime.Now.TimeOfDay);
                return new TaskSchedule() { Interval = newTime.TotalMilliseconds, RunTaskImmediately = false };
            }
        }
    }
}
